package com.njworkorder.adapter;

import cn.microvideo.qsc.client.entity.Role;
import cn.microvideo.qsc.client.entity.xml.ParentRoles;
import cn.microvideo.qsc.client.utils.BasecodeUtil;
import cn.microvideo.qsc.client.utils.InputStreamHelper;
import cn.microvideo.qsc.client.utils.RequestMethod;
import cn.microvideo.qsc.client.utils.SAXHelper;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.security.AnyTypePermission;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class QsApiAdapter {

    @Value("${qs.serverUrl}")
    private String path;

    @Value("${qs.secretKey}")
    private String qsSecret;


    public Document getDoc(String service, RequestMethod method, Map<String, String> params) {
        InputStream in = InputStreamHelper.getInputStream(service, method, params, "");
        return SAXHelper.getDocument(in);
    }


    public List<Role> findPersonRole(String uid) {
        String service = this.path + "service/findRoleByUid";
        Map<String, String> params = new HashMap();
        params.put("uid", BasecodeUtil.enString(uid));
        Document doc = this.getDoc(service, RequestMethod.GET, params);
        XStream xstream = new XStream(new DomDriver());
        xstream.addPermission(AnyTypePermission.ANY);
        xstream.alias("info", ParentRoles.class);
        xstream.autodetectAnnotations(true);
        try {
            ParentRoles info = (ParentRoles) xstream.fromXML(doc.asXML());
            return info.getRoles().getRoleList();
        } catch (NullPointerException e) {
            return Collections.emptyList();
        } catch (Exception e) {
            log.error("get person role error", e);
            return Collections.emptyList();
        }
    }




}
